﻿using System;
using System.Collections.Generic;
using System.Data;
using ContractManager.BLL.Business;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using System.Windows.Forms;
using ContractManager.Entity;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;

namespace ContractManager.Lists.Contracts
{
    public partial class FrmRevenuesDetail : XtraFormBase
    {
        #region "Private Variable"
        
        public bool SaveClose;
        public bool SaveNew;
        public bool OnlyView;
        public int MasterId;
        
        #endregion

        #region "Form Construction"
        public FrmRevenuesDetail()
        {
            InitializeComponent();
        }
        #endregion

        #region "Private Method"

        private void BlankForm()
        {
            this.ResetControls();
            grdDetail.DataSource = ClsRevenues.ListDetail(0);
        }

        private void LoadLookupData()
        {
            txtConId.Properties.DataSource = ClsContracts.GetLookupAll();
            txtConId.Properties.DisplayMember = "ConNo";
            txtConId.Properties.ValueMember = "ConId";
        }

        private void GetDetail()
        {
            var detail = ClsRevenues.SelectByPk(MasterId);
            if (detail != null)
            {
                txtRevNo.EditValue = String.Format("{0}",detail.RevNo);
                txtRevDate.EditValue = detail.RevDate;
                txtConId.EditValue = detail.ConId;
                txtRevDescription.EditValue = detail.RevDescription;
                txtCustomField1.EditValue = String.Format("{0}", detail.CustomField1);
                txtCustomField2.EditValue = String.Format("{0}", detail.CustomField2);
                txtCustomField3.EditValue = String.Format("{0}", detail.CustomField3);
                txtCustomField4.EditValue = String.Format("{0}", detail.CustomField4);
                txtCustomField5.EditValue = String.Format("{0}", detail.CustomField5);
                txtCustomField6.EditValue = String.Format("{0}", detail.CustomField6);
                txtCustomField7.EditValue = String.Format("{0}", detail.CustomField7);
                txtCustomField8.EditValue = String.Format("{0}", detail.CustomField8);
                txtCustomField9.EditValue = String.Format("{0}", detail.CustomField9);
                txtCustomField10.EditValue = String.Format("{0}", detail.CustomField10);

                grdDetail.DataSource = ClsRevenues.ListDetail(MasterId);

                if (this.LstLockDate.Contains(Convert.ToDateTime(detail.RevDate).Date))
                {
                    OnlyView = true;
                    btnSaveNew.Enabled = !OnlyView;
                    btnSave.Enabled = !OnlyView;
                    btnSaveClose.Enabled = !OnlyView;
                    btnDelete.Enabled = !OnlyView && this.AllowDelete;
                    btnDesign.Enabled = !OnlyView;
                }
            } 
  

        }

        private void DoSave()
        {
            grdDetail.EmbeddedNavigator.Buttons.DoClick(grdDetail.EmbeddedNavigator.Buttons.EndEdit);

            #region "Variable"
            
            DataTable dtSource = (DataTable)grdDetail.DataSource;

            #endregion

            #region "Check Condition"
            //if (!FormIsNotValidate)
            //{
            //    if (!dxValidationProvider.Validate())
            //    {
            //        XtraMessageBox.Show(
            //                    "Vui lòng nhập đầy đủ thông tin trước khi lưu",
            //                    "Thông báo",
            //                    MessageBoxButtons.OK,
            //                    MessageBoxIcon.Error);
            //        txtCode.SelectAll();
            //        txtCode.Focus();
            //        return;
            //    }
            //}
            if (LstLockDate.Contains(txtRevDate.DateTime.Date))
            {
                XtraMessageBox.Show(
                                "Ngày chứng từ đã bị khoá sổ. Vui lòng nhập ngày khác",
                                "Thông báo",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                txtRevDate.SelectAll();
                txtRevDate.Focus();
                return;
            }
            if (dtSource.Rows.Count == 0)
            {
                XtraMessageBox.Show(
                            "Số lượng công việc trong hợp đồng phải >0.",
                            "Thông báo",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                txtRevNo.SelectAll();
                txtRevNo.Focus();
                return;
            }
            #endregion

            var item = MasterId <= 0 ? new Revenues() : ClsRevenues.SelectByPk(MasterId);
            item.RevNo = String.Format("{0}", txtRevNo.EditValue);
            item.RevDate = txtRevDate.DateTime;
            item.ConId = Convert.ToInt32(txtConId.EditValue);
            item.RevDescription = String.Format("{0}", txtConName.EditValue);
            
            item.CustomField1 = String.Format("{0}", txtCustomField1.EditValue);
            item.CustomField2 = String.Format("{0}", txtCustomField2.EditValue);
            item.CustomField3 = String.Format("{0}", txtCustomField3.EditValue);
            item.CustomField4 = String.Format("{0}", txtCustomField4.EditValue);
            item.CustomField5 = String.Format("{0}", txtCustomField5.EditValue);
            item.CustomField6 = String.Format("{0}", txtCustomField6.EditValue);
            item.CustomField7 = String.Format("{0}", txtCustomField7.EditValue);
            item.CustomField8 = String.Format("{0}", txtCustomField8.EditValue);
            item.CustomField9 = String.Format("{0}", txtCustomField9.EditValue);
            item.CustomField10 = String.Format("{0}", txtCustomField10.EditValue);

            item.FormId = FormNo;
            item.VoucherCate = VoucherCate;

            item.ListAdd = GetListAdd(dtSource.GetChanges(DataRowState.Added));
            item.ListUpdate = GetListUpdate(dtSource.GetChanges(DataRowState.Modified));
            item.ListDelete = GetListDelete(dtSource.GetChanges(DataRowState.Deleted));
            try
            {
                if (MasterId > 0)
                {
                    item.UpdateBy = ClsVariable.EmployeeId;
                    item.UpdateDate = DateTime.Now;
                    ClsRevenues.Update(item); 
                }
                else
                {
                    item.CreateBy = ClsVariable.EmployeeId;
                    item.CreateDate = DateTime.Now;
                    ClsRevenues.Insert(item);
                    MasterId = item.RevId;
                }

                dtSource.AcceptChanges();
                grdDetail.DataSource = ClsRevenues.ListDetail(MasterId);

                if (SaveNew)
                {
                    MasterId = 0;
                    BlankForm();
                    txtRevNo.Focus();
                    
                }
                else if (SaveClose)
                {
                    Close();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                    String.Format("Có lỗi xảy ra trong quá trình cập nhật dữ liệu. {0}", ex.Message),
                    "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void DoDelete()
        {
            if (MasterId <= 0) return;
            
            try
            {
                if (
                        XtraMessageBox.Show(
                                        "Bạn có muốn xóa bản ghi này không?",
                                        "Thông báo",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question) == DialogResult.No) return;
                ClsRevenues.DeleteByPk(MasterId);
                Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                       "Có lỗi xảy ra trong quá trình xóa dữ liệu. " + ex.Message,
                       "Thông báo",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
            }
        }

        private List<RevenueDetails> GetListAdd(DataTable dataTable)
        {
            List<RevenueDetails> list = new List<RevenueDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    RevenueDetails item = new RevenueDetails();
                    item.RevDetId = 0;
                    item.ConDetId = Convert.ToInt32(row["ConDetId"]);
                    item.RevDetDescription = String.Format("{0}", row["RevDetDescription"]);
                    item.RevDetPayAmount = row["RevDetPayAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetPayAmount"]);
                    item.RevDetVatRate = row["RevDetVatRate"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetVatRate"]);
                    item.RevDetVatAmount = row["RevDetVatAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetVatAmount"]);
                    item.RevDetInsRate = row["RevDetInsRate"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetInsRate"]);
                    item.RevDetInsAmount = row["RevDetInsAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetInsAmount"]);
                    item.RevDetInsAfterAmount = row["RevDetInsAfterAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetInsAfterAmount"]);
                    item.RevDetExcRate = row["RevDetExcRate"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetExcRate"]);
                    item.RevDetAmount = row["RevDetAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetAmount"]);
                    item.RevTranAmount = row["RevTranAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevTranAmount"]);
                    item.RevDetBalanceAmount = row["RevDetBalanceAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetBalanceAmount"]);

                    item.CustomField1 = String.Format("{0}", row["CustomField1"]);
                    item.CustomField2 = String.Format("{0}", row["CustomField2"]);
                    item.CustomField3 = String.Format("{0}", row["CustomField3"]);
                    item.CustomField4 = String.Format("{0}", row["CustomField4"]);
                    item.CustomField5 = String.Format("{0}", row["CustomField5"]);

                    list.Add(item);
                    
                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<RevenueDetails> GetListUpdate(DataTable dataTable)
        {
            List<RevenueDetails> list = new List<RevenueDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    RevenueDetails item = new RevenueDetails();
                    item.RevDetId = Convert.ToInt32(row["RevDetId"]); 
                    item.ConDetId = Convert.ToInt32(row["ConDetId"]);
                    item.RevDetDescription = String.Format("{0}", row["RevDetDescription"]);
                    item.RevDetPayAmount = row["RevDetPayAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetPayAmount"]);
                    item.RevDetVatRate = row["RevDetVatRate"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetVatRate"]);
                    item.RevDetVatAmount = row["RevDetVatAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetVatAmount"]);
                    item.RevDetInsRate = row["RevDetInsRate"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetInsRate"]);
                    item.RevDetInsAmount = row["RevDetInsAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetInsAmount"]);
                    item.RevDetInsAfterAmount = row["RevDetInsAfterAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetInsAfterAmount"]);
                    item.RevDetExcRate = row["RevDetExcRate"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetExcRate"]);
                    item.RevDetAmount = row["RevDetAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetAmount"]);
                    item.RevTranAmount = row["RevTranAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevTranAmount"]);
                    item.RevDetBalanceAmount = row["RevDetBalanceAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["RevDetBalanceAmount"]);

                    item.CustomField1 = String.Format("{0}", row["CustomField1"]);
                    item.CustomField2 = String.Format("{0}", row["CustomField2"]);
                    item.CustomField3 = String.Format("{0}", row["CustomField3"]);
                    item.CustomField4 = String.Format("{0}", row["CustomField4"]);
                    item.CustomField5 = String.Format("{0}", row["CustomField5"]);

                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<RevenueDetails> GetListDelete(DataTable dataTable)
        {
            List<RevenueDetails> list = new List<RevenueDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    RevenueDetails item = new RevenueDetails();
                    item.RevDetId = Convert.ToInt32(row["RevDetId", DataRowVersion.Original]);
                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private void GetContractInfor(int conId)
        {
            var detail = ClsContracts.SelectByPk(conId);
            if (detail != null)
            {
                txtConDate.EditValue = detail.ConDate;
                txtConName.EditValue = String.Format("{0}", detail.ConName);
                txtConAmount.EditValue = detail.ConAmount;
                txtConSetAmount.EditValue = detail.ConSetAmount;
                txtConSentDate.EditValue = detail.ConSentDate;
                txtConReceiptDate.EditValue = detail.ConReceiptDate;
                txtConDescription.EditValue = String.Format("{0}", detail.ConDescription);

                ContractDetailSearchLookUpEdit.DataSource = ClsContracts.ListDetail(conId);
                ContractDetailSearchLookUpEdit.DisplayMember = "ConDetContent";
                ContractDetailSearchLookUpEdit.ValueMember = "ConDetId";
            }
        }

        #endregion

        #region "Form Event"
        private void FrmRevenuesDetailLoad(object sender, EventArgs e)
        {
            BlankForm();
            LoadLookupData();
            if (MasterId > 0) GetDetail();
            btnSaveNew.Enabled = !OnlyView;
            btnSave.Enabled = !OnlyView;
            btnSaveClose.Enabled = !OnlyView;
            btnDelete.Enabled = !OnlyView && this.AllowDelete;
            btnDesign.Enabled = !OnlyView;
            if (!String.IsNullOrEmpty(FormXtraLayoutTemplate))
            {
                var fileLayout = ClsVariable.GetRestoreLayoutFullPath(FormXtraLayoutTemplate);
                layoutControl.RestoreLayoutFromXml(fileLayout);
            }
            if (!String.IsNullOrEmpty(FormXtraGridLayoutTemplate))
            {
                var filePath = ClsVariable.GetRestoreLayoutFullPath(FormXtraGridLayoutTemplate);
                grvDetail.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
            }
        }
        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnSave":
                    DoSave();
                    break;
                case "btnSaveNew"://Lưu và thêm mới
                    SaveNew = true;
                    DoSave();
                    break;
                case "btnSaveClose"://Lưu và đóng
                    SaveClose = true;
                    DoSave();
                    break;
                case "btnDelete":
                    DoDelete();
                    break;
                case "btnDesign":
                    ClsVariable.ShowDesignXtraGrid(grdDetail);
                    break;
                case "btnRefresh"://Nạp lại danh mục
                    break;
                case "btnHistory"://History
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }
        #endregion

        #region "Lookup Event"
        private void txtConId_EditValueChanged(object sender, EventArgs e)
        {
            if (txtConId.EditValue != null)
            {
                int contId = Convert.ToInt32(txtConId.EditValue);
                GetContractInfor(contId);
            }
        }

        #endregion

        #region "XtraGrid Event"
        private void grvDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Value == null) return;
            var view = (GridView)sender;
            decimal dPayAmount, dVatRate, dVatAmount, dInsRate, dInsAmount,dInsAfterAmount, dExcRate, dDetAmount, dTranAmount, dBalanceAmount; 

            switch (e.Column.FieldName)
            {
                case "ConDetId"://Noi dung cong viec
                    int conDetId = Convert.ToInt32(e.Value);
                    var item = ClsContractDetails.SelectByPk(conDetId);
                    if (item != null)
                    {
                        view.SetRowCellValue(e.RowHandle, "ConDetAmount", item.ConDetAmount);
                        view.SetRowCellValue(e.RowHandle, "ConDetSetAmount", item.ConDetSetAmount);
                        view.SetRowCellValue(e.RowHandle, "ConDetStartDate", item.ConDetStartDate);
                        view.SetRowCellValue(e.RowHandle, "ConDetEndDate", item.ConDetEndDate);
                        view.SetRowCellValue(e.RowHandle, "ConDetPlanEndDate", item.ConDetPlanEndDate);
                        view.SetRowCellValue(e.RowHandle, "ConDetNumDay", item.ConDetNumDay);
                        if (item.MbID != null)
                        {
                            var mbItem = ClsMemberBranch.SelectByPk(Convert.ToInt32(item.MbID));
                            view.SetRowCellValue(e.RowHandle, "MbID", mbItem.MbName);
                        }
                        view.SetRowCellValue(e.RowHandle, "ConDetCtManager", item.ConDetCtManager);
                        view.SetRowCellValue(e.RowHandle, "ConDetLeader", item.ConDetLeader);
                        if (item.WorkId != null)
                        {
                            var wkItem = ClsWorkType.SelectByPk(Convert.ToInt32(item.WorkId));
                            view.SetRowCellValue(e.RowHandle, "WorkId", wkItem.WorkName);
                        }
                        view.SetRowCellValue(e.RowHandle, "RevDetVatRate", item.ConDetVatRate);
                        view.SetRowCellValue(e.RowHandle, "ConDetDecisionNo", item.ConDetDecisionNo);
                        view.SetRowCellValue(e.RowHandle, "ConDetAllocationDecision", item.ConDetAllocationDecision);
                        view.SetRowCellValue(e.RowHandle, "ConDetInsRate", item.ConDetInsRate);
                        view.SetRowCellValue(e.RowHandle, "ConDetExcRate", item.ConDetExcRate);
                        view.SetRowCellValue(e.RowHandle, "ConDetInsAmount", item.ConDetInsAmount);
                        view.SetRowCellValue(e.RowHandle, "ConDetInsAfterAmount", item.ConDetInsAfterAmount);
                        view.SetRowCellValue(e.RowHandle, "ConDetExcAmount", item.ConDetExcAmount);
                    }
                    break;
                case "RevDetPayAmount":
                    if (e.Value != null && e.Value != DBNull.Value)
                    {
                        dPayAmount = Convert.ToDecimal(e.Value);
                        dVatRate = view.GetRowCellValue(e.RowHandle, "RevDetVatRate") == null
                            || view.GetRowCellValue(e.RowHandle, "RevDetVatRate") == DBNull.Value ? 0 :
                                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "RevDetVatRate"));
                        dInsRate = view.GetRowCellValue(e.RowHandle, "ConDetInsRate") == null
                            || view.GetRowCellValue(e.RowHandle, "ConDetInsRate") == DBNull.Value ? 0 :
                                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "ConDetInsRate"));
                        dExcRate = view.GetRowCellValue(e.RowHandle, "ConDetExcRate") == null
                            || view.GetRowCellValue(e.RowHandle, "ConDetExcRate") == DBNull.Value ? 0 :
                                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "ConDetExcRate"));

                        dVatAmount = Math.Round(dPayAmount / (1 + dVatRate));
                        dInsAmount = Math.Round(dInsRate * dVatAmount);
                        dInsAfterAmount = Math.Round(dVatAmount - dInsAmount);
                        dDetAmount = Math.Round(dExcRate * dInsAfterAmount);
                        
                        view.SetRowCellValue(e.RowHandle, "RevDetVatAmount", dVatAmount);
                        view.SetRowCellValue(e.RowHandle, "RevDetInsAmount", dInsAmount);
                        view.SetRowCellValue(e.RowHandle, "RevDetInsAfterAmount", dInsAfterAmount);
                        view.SetRowCellValue(e.RowHandle, "RevDetAmount", dDetAmount);
                    }
                    break;
                //case "RevDetVatRate":
                //    if (e.Value != null && e.Value != DBNull.Value)
                //    {
                //        dVatRate = Convert.ToDecimal(e.Value);
                //        dPayAmount = view.GetRowCellValue(e.RowHandle, "RevDetPayAmount") == null
                //            || view.GetRowCellValue(e.RowHandle, "RevDetPayAmount") == DBNull.Value ? 0 :
                //                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "RevDetPayAmount"));

                //        dVatAmount = Math.Round(dPayAmount/(1+dVatRate));

                //        view.SetRowCellValue(e.RowHandle, "RevDetVatAmount", dVatAmount);
                //    }
                //    break;
                //case "RevDetInsRate":
                //    dInsRate = Convert.ToDecimal(e.Value);
                //    dVatAmount = view.GetRowCellValue(e.RowHandle, "RevDetVatAmount") == null
                //            || view.GetRowCellValue(e.RowHandle, "RevDetVatAmount") == DBNull.Value ? 0 :
                //                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "RevDetVatAmount"));
                //    dInsAmount = Math.Round(dInsRate * dVatAmount);
                //    view.SetRowCellValue(e.RowHandle, "RevDetInsAmount", dInsAmount);
                //    break;
                //case "RevDetInsAmount":
                //    dInsAmount = Convert.ToDecimal(e.Value);
                //    dVatAmount = view.GetRowCellValue(e.RowHandle, "RevDetVatAmount") == null
                //            || view.GetRowCellValue(e.RowHandle, "RevDetVatAmount") == DBNull.Value ? 0 :
                //                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "RevDetVatAmount"));

                //    dInsAfterAmount = Math.Round(dVatAmount - dInsAmount);
                //    view.SetRowCellValue(e.RowHandle, "RevDetInsAfterAmount", dInsAfterAmount);
                //    break;
                //case "RevDetExcRate":
                //    dExcRate = Convert.ToDecimal(e.Value);
                //    dInsAfterAmount = view.GetRowCellValue(e.RowHandle, "RevDetInsAfterAmount") == null
                //            || view.GetRowCellValue(e.RowHandle, "RevDetInsAfterAmount") == DBNull.Value ? 0 :
                //                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "RevDetInsAfterAmount"));
                //    dDetAmount = Math.Round(dExcRate * dInsAfterAmount);
                //    view.SetRowCellValue(e.RowHandle, "RevDetAmount", dDetAmount);
                //    break;
                case "RevTranAmount":
                    dTranAmount = Convert.ToDecimal(e.Value);
                    dDetAmount = view.GetRowCellValue(e.RowHandle, "RevDetAmount") == null
                            || view.GetRowCellValue(e.RowHandle, "RevDetAmount") == DBNull.Value ? 0 :
                                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "RevDetAmount"));
                    dBalanceAmount = dDetAmount - dTranAmount;
                    view.SetRowCellValue(e.RowHandle, "RevDetBalanceAmount", dBalanceAmount);
                    break;
               
            }
        }

        #endregion

    }
}
